package com.hiwhitley.chapter03;

/**
 * Created by hiwhitley on 17-2-17.
 */
public class IfBalanceTree {

    public boolean isBalance(Node head) {
        return getHeight(head, 0) != -1;
    }

    private int getHeight(Node head, int level) {
        if (head == null) {
            return level;
        }

        int lh = getHeight(head.left, level + 1);
        int rh = getHeight(head.right, level + 1);

        if (lh == -1 || rh == -1 || Math.abs(lh - rh) > 1) {
            return -1;
        }

        return Math.max(lh, rh);
    }

}
